﻿Imports System.Data
Imports System.Data.SqlClient
Imports System.Net.Mail
Imports System.Text
Imports System.IO
Imports System.Xml.Serialization
Imports System.Text.Encoding
Imports Abyx.SVCMS.Library.DB

Friend Class Utility

    Shared Function GetList(ByVal CommandObject As Data.SqlClient.SqlCommand) As DataTable
        Dim dt As New DataTable
        Dim red As SqlDataReader
        Try
            red = CommandObject.ExecuteReader
            dt.Load(red)
        Catch ex As Exception
            Throw ex
        End Try
        Return dt
    End Function

    Shared Function GetUniqueFieldList(ByVal CommandObject As Data.SqlClient.SqlCommand) As ObjectModel.Collection(Of String)
        Dim rt As New ObjectModel.Collection(Of String)
        Dim dt As New DataTable
        Dim red As SqlDataReader
        Try
            red = CommandObject.ExecuteReader
            dt.Load(red)
            For Each row As DataRow In dt.Rows
                rt.Add(row(0).ToString)
            Next
        Catch ex As Exception
            Throw ex
        End Try
        Return rt
    End Function

    Shared Function IsDatesOverlapping(ByVal period1_start As Date, _
                                       ByVal period1_end As Date, _
                                       ByVal period2_start As Date, _
                                       ByVal period2_end As Date) As Boolean
        If Date.Compare(period1_start, period2_end) < 0 And Date.Compare(period1_end, period2_start) > 0 Then
            Return True
        End If
        Return False
    End Function

    Shared Function SendMail(ByVal Subject As String, _
                      ByVal Body As String, _
                      ByVal ToAddress As String, _
                      Optional ByVal cc As String = Nothing, _
                      Optional ByVal Bcc As String = Nothing, _
                      Optional ByVal MailAttachment As String = Nothing) As Boolean
        Dim ReturnValue As Boolean = True
        Return ReturnValue
    End Function


#Region "Checks, Tests, RecordCount"
    Shared Function DataBaseConnectivityTest() As Boolean

        Dim cmd As New SqlCommand("SELECT * FROM sysobjects WHERE xtype = 'U'")
        Try
            Using con As New SqlConnection(Utility.GetConnectionString)
                con.Open()

                cmd.Connection = con
                cmd.ExecuteNonQuery()

                con.Close()
            End Using
        Catch ex As Exception
            Return False
        End Try

        Return True
    End Function
    Shared Function GetRecordCount(ByVal cmd As SqlCommand, _
                                   Optional ByRef RecordExists As Boolean = True) As Int32
        Try
            Dim i As Object = cmd.ExecuteScalar
            If IsNothing(i) = True Then
                RecordExists = False
                Return 0
            End If
            Dim j As Int32 = Int32.Parse(i)
            If j = 0 Then Return 0 Else Return j
        Catch ex As Exception
            Throw ex
        End Try
    End Function
#End Region

#Region "Settings"

    Shared Function GetConnectionString() As String
        Dim settings As SettingsType = Utility.Settings_Read
        Dim conStr As String = Utility.DecryptData_3DES(settings.DbSettings.ConnectionString)
        Return conStr
    End Function

    Shared Sub SetConnectoinString(ConnectionString As String)
        Dim settings As SettingsType = Utility.Settings_Read
        Dim conStr As String = Utility.EncriptData_3DES(ConnectionString)
        settings.DbSettings.ConnectionString = conStr
        Utility.Settings_Write(settings)
    End Sub

    Shared Function Settings_Read() As SettingsType

        Dim Settings As New SettingsType()
        Try
            Dim objStreamReader As New StreamReader(Utility.Settings_GetFilePath)
            Dim x As New XmlSerializer(GetType(SettingsType))
            Settings = x.Deserialize(objStreamReader)
            objStreamReader.Close()
        Catch ex1 As FileNotFoundException
            'if settings do not exist write defailt settings file
            Try
                Utility.Settings_Write(Settings)
            Catch ex2 As Exception
                Throw ex2
            End Try
        Catch ex1 As Exception
            Throw ex1
        End Try

        Return Settings

    End Function

    Shared Sub Settings_Write(ByVal Settings As SettingsType)

        Try
            If Not Settings Is Nothing Then
                Dim objStreamWriter As New StreamWriter(Utility.Settings_GetFilePath)
                Dim x As New XmlSerializer(GetType(SettingsType))
                x.Serialize(objStreamWriter, Settings)
                objStreamWriter.Close()
            End If
        Catch ex As Exception
            Throw ex
        End Try

    End Sub

    Shared Function Settings_GetFilePath() As String
        Dim sfPath As String = My.Computer.FileSystem.SpecialDirectories.AllUsersApplicationData
        If sfPath.EndsWith("\") = False Then sfPath &= "\"
        Return sfPath & "\SVCMS.Library.Settings.xml"
    End Function

#End Region

#Region "Security"
    Shared Function HashBytes_SHA512(ByVal DataToHash() As Byte) As Byte()
        Return New Security.Cryptography.SHA512Managed().ComputeHash(DataToHash)
    End Function
    Shared Function HashBytes_SHA512(ByVal DataToHash As String) As String
        Dim bData() As Byte = ASCIIEncoding.ASCII.GetBytes(DataToHash)
        Dim bHashedData() As Byte = HashBytes_SHA512(bData)
        Return System.Text.Encoding.Default.GetString(bHashedData)
    End Function
    Shared Function EncriptData_3DES(ByVal rawData As String) As String
        Dim rj As New TrippleDesEncryption
        Return rj.EncryptData(rawData)
    End Function
    Shared Function EncriptData_3DES(ByVal rawData() As Byte) As String
        Dim rj As New TrippleDesEncryption
        Return rj.EncryptData(rawData)
    End Function
    Shared Function DecryptData_3DES(ByVal encData As String) As String
        Dim rj As New TrippleDesEncryption
        Return rj.DecryptData(encData)
    End Function
    Shared Function DecryptData_3DES_Bytes(ByVal encData As String) As Byte()
        Dim rj As New TrippleDesEncryption
        Return rj.DecryptData_Bytes(encData)
    End Function
#End Region

#Region "Formatting Functions"
    Shared Function DateFormatDisplay(ByVal sampleDate As DateTime) As String
        Return Format(sampleDate, "dd-MMM-yy hh:mm:ss")
    End Function
    Shared Function DateFormatSql(ByVal sampleDate As DateTime) As String
        Return Format(sampleDate, "yyyy-MM-dd HH:mm:ss")
    End Function
    Shared Function FileNameFormatSqlUpdates(VersionNumber As Integer) As String
        Return "SVCM-" & Format(VersionNumber, "00000") & ".sql"
    End Function
#End Region

End Class

